﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

namespace CrmClient.Mapping
{
    public abstract class CrmDataContractBase
    {
        private static Dictionary<string, Type> _dataContracts = new Dictionary<string, Type>();
        private static Dictionary<Type, string> _entityNames = new Dictionary<Type, string>();
        static CrmDataContractBase()
        {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                foreach (var type in a.GetTypes())
                    if (type.BaseType == typeof(CrmDataContractBase))
                    {
                        var logicalName = MappingUtils.GetCrmEntityName(type);
                        _dataContracts.Add(logicalName, type);
                        _entityNames.Add(type, logicalName);
                    }
        }

        public abstract Guid Id { get; set; }

        public EntityReference ToEntityReference()
        {
            var dstEntityName = _entityNames[this.GetType()];
            return new EntityReference(dstEntityName, Id);
        }
    }
}
